<template>
  <input-with-dialog
    ref="inputWithDialog"
    v-model="valueDialog"
    class="c-single-dialog"
    :props="props"
    v-bind="$attrs"
    @change="changeHandle"
    @blur="blurHandle"
  />
</template>
<script>
export default {
  name: 'CSingleDialog',
  props: {
    props: {
      type: Object,
      default: () => ({ label: 'label', value: 'value' })
    },
    value: {
      type: [String, Number],
      default: ''
    },
    label: {
      type: [String, Number],
      default: ''
    }
  },
  data() {
    return {
      valueDialog: []
    }
  },
  watch: {
    valueDialog: {
      handler(v) {
        if (v.length === 0) {
          this.$emit('input', '')
          this.$emit('update:label', '')
        } else {
          this.$emit('input', v[0][this.props.value])
          this.$emit('update:label', v[0][this.props.label])
        }
      }
    },
    value: {
      handler(v) {
        const vd = this.valueDialog
        if (vd.length > 0 && vd[0][this.props.value] === this.value && vd[0][this.props.label] === this.label) {
          return
        }
        this.valueDialog = [
          { [this.props.label]: this.label, [this.props.value]: this.value }
        ]
      },
      immediate: true
    },
    label: {
      handler(v) {
        const vd = this.valueDialog
        if (vd.length > 0 && vd[0][this.props.value] === this.value && vd[0][this.props.label] === this.label) {
          return
        }
        this.valueDialog = [
          { [this.props.label]: this.label, [this.props.value]: this.value }
        ]
      },
      immediate: true
    }
  },
  methods: {
    searchData(...args) {
      return this.$refs.inputWithDialog.searchData(...args)
    },
    openDialog(...args) {
      return this.$refs.inputWithDialog.openDialog(...args)
    },
    changeHandle(data) {
      if (data.length === 0) {
        data = {}
      } else {
        data = data[0]
      }
      this.$emit('change', data)
    },
    blurHandle(...args) {
      this.$emit('blur', ...args)
    }
  }
}
</script>
<style lang="scss" scoped>
.c-single-dialog{
  display: inline-block;
}
</style>
